package it.tcm.TeacherClassMate.servlet;

import java.util.Calendar;
import java.util.Date;
import java.util.Timer;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class MyServletContextListener implements ServletContextListener {
	
	public void contextInitialized(ServletContextEvent servletContextEvent) {
		
		ServletContext servletContext = servletContextEvent.getServletContext();
		try{
		 // create the timer and timer task objects
		  Timer timer = new Timer();
		 MyTimerTask task = new MyTimerTask();

		 // get a calendar to initialize the start time
		  Calendar calendar = Calendar.getInstance();
		 Date startTime = calendar.getTime();

		  // schedule the task to run 
		 timer.scheduleAtFixedRate(task, startTime, 1000 * 60 * 1);

		  // save our timer for later use
		  servletContext.setAttribute ("timer", timer);
		} catch (Exception e) {
		 servletContext.log ("Problem initializing the task that was to run hourly: " + e.getMessage ());
		}
		
	}
	
	public void contextDestroyed(ServletContextEvent servletContextEvent) {
		
		ServletContext servletContext = servletContextEvent.getServletContext();

		// get our timer from the Context
		Timer timer = (Timer)servletContext.getAttribute ("timer");

		// cancel all pending tasks in the timers queue
		if (timer != null)
		timer.cancel();

		// remove the timer from the servlet context
		servletContext.removeAttribute ("timer");
		
	}

}
